package ai.people.netmon.telegram.service.impl;

import ai.people.netmon.framework.domain.telegram.entity.Users;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.telegram.domain.request.channels.UsersRequest;
import ai.people.netmon.telegram.mapper.ManageUsersMapper;
import ai.people.netmon.telegram.service.ManageUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 管理系统-用户服务impl
 *
 * @author yuanqinglong
 * @date 2022/1/7 16:45
 */
@Service
public class ManageUserServiceImpl implements ManageUserService {

    /**
     * 管理用户映射器
     */
    @Autowired
    private ManageUsersMapper manageUsersMapper;


    /**
     * 分页查询用户
     *
     * @param usersConditions 用户环境
     * @return {@link PageResponse}<{@link Users}>
     */
    @Override
    public PageResponse<Users> selectUserPage(UsersRequest usersConditions) {
        Page<Users> page = new Page<>(usersConditions.getPageNo(), usersConditions.getPageSize());
        LambdaQueryWrapper<Users> conditions = usersConditions.createConditions();
        Page<Users> usersPage = manageUsersMapper.selectPage(page, conditions);
        return PageResponse.builder(usersPage.getRecords(), usersPage.getTotal());
    }

    /**
     * 通过id查询用户
     *
     * @param userId 用户id
     * @return {@link Users}
     */
    @Override
    public Users selectById(Long userId) {
        LambdaQueryWrapper<Users> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(Users::getId, userId);
        Users users = manageUsersMapper.selectOne(lambdaQuery);
        if (Objects.isNull(users)) {
            // TODO: 2022/1/7 用户不存在异常
        }
        return users;
    }

    /**
     * 添加用户
     *
     * @param users 用户
     * @return int
     */
    @Override
    public int addUser(Users users) {
        return manageUsersMapper.insert(users);
    }

    /**
     * 更新用户
     *
     * @param users 用户
     * @return int
     */
    @Override
    public int updateUserById(Users users) {
        // 校验用户是否存在
        this.selectById(users.getId());
        return manageUsersMapper.updateById(users);
    }

    /**
     * 删除用户
     *
     * @param userId 用户id
     * @return int
     */
    @Override
    public int deleteUserById(Long userId) {
        return manageUsersMapper.deleteById(userId);
    }
}
